package uns.fit.gis.mapdrawer;

import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.game.Sprite;

import uns.fit.gis.mapobj.Segment;

public class ArrowDrawer {
	private Sprite arrow;
	
	public ArrowDrawer(Image arrow){
		this.arrow = new Sprite(arrow, 16, 16);
		this.arrow.defineReferencePixel(8, 8);
	}
	
	/*
	 * yAsc = true: chieu duong tu tren xuong duoi (y tang dan)
	 * yAsc = false: chieu duong tu duoi len tren (y giam dan)
	 */
	public void draw(Graphics g, int x0, int y0, int x1, int y1, boolean yAsc){
		
		if(y0 > y1) {
			int temp = x0;
			x0 = x1;
			x1 = temp;
			temp = y0;
			y0 = y1;
			y1 = temp;
		}
		
		int angle = getAngle(x0, y0, x1, y1);
		int transform = Sprite.TRANS_NONE;
		if(yAsc) {
			if(angle == 90) {
				arrow.setFrame(0);
				transform = Sprite.TRANS_ROT90;
			}
			else
				arrow.setFrame(angle / 10);
			
			if(x1 < x0)
				transform = Sprite.TRANS_MIRROR;
			
		}
		else {
			if(angle == 90) {
				arrow.setFrame(0);
				transform = Sprite.TRANS_ROT270;
			}
			else {
				arrow.setFrame(angle / 10);
				transform = Sprite.TRANS_ROT180;
			}
			
			if(x1 < x0)
				transform = Sprite.TRANS_MIRROR_ROT180;
			
		}
		/*
			System.out.println("Arrow");
			System.out.println(yAsc);
			System.out.println("X0 = " + x0);
			System.out.println("Y0 = " + y0);
			System.out.println("X1 = " + x1);
			System.out.println("Y1 = " + y1);
			System.out.println("Transform = " + transform);
		*/
		
		arrow.setTransform(transform);
		int dx = (x1 - x0);
		int dy = Math.abs(y1 - y0);
		arrow.setRefPixelPosition(x0 + dx / 2, y0 + dy / 2);
		arrow.paint(g);
	}
	
	public static int getAngle(int x0, int y0, int x1, int y1) {
		if(x1 == x0)
			return 90;
		int tanX1000 = (int)(1000 * Math.abs(y1 - y0) * 1.0 / Math.abs(x1 - x0));
		//System.out.println("Tan = " + tanX1000);
		int angle = 80;
		if(tanX1000 < 176)
			angle = 0;
		else if(tanX1000 < 363)
			angle = 10;
		else if(tanX1000 < 577)
			angle = 20;
		else if(tanX1000 < 839)
			angle = 30;
		else if(tanX1000 < 1192)
			angle = 40;
		else if(tanX1000 < 1732)
			angle = 50;
		else if (tanX1000 < 2747)
			angle = 60;
		else if(tanX1000 < 5671)
			angle = 70;
		//System.out.println("Angle = " + angle);
		return angle;
	}
}
